<template>
  <div class="my-characters">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">我的角色</h1>
        <p class="page-description">管理你创建的所有AI角色</p>
      </div>
      <el-button type="primary" :icon="Plus" @click="goToCreateCharacter">
        创建角色
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="charactersLoading" class="loading-container">
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
      <el-skeleton :rows="3" animated />
    </div>

    <!-- 角色卡片网格 -->
    <div v-else class="character-grid">
      <!-- 动态角色卡片 -->
      <el-card 
        v-for="character in characters" 
        :key="character.id" 
        class="character-card" 
        shadow="hover"
        @click="showCharacterDetail(character.id)"
      >
        <div class="character-avatar">
          <el-avatar 
            :size="80" 
            :src="character.image" 
            :icon="User"
          />
        </div>
        <div class="character-info">
          <h3 class="character-name">{{ character.name }}</h3>
          <p class="character-desc">{{ character.appearance }}</p>
          <div class="character-meta">
            <el-tag :type="character.isPublic ? 'success' : 'info'" size="small">
              {{ character.isPublic ? '公开' : '私有' }}
            </el-tag>
            <span class="create-time" v-if="character.createTime">
              {{ formatDate(character.createTime) }}
            </span>
          </div>
        </div>
        <div class="character-actions">
          <el-button size="small" type="primary" @click.stop="editCharacter(character.id)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click.stop="deleteCharacter(character.id)">
            删除
          </el-button>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-if="characters && characters.length === 0" class="empty-state">
        <el-empty description="还没有创建任何角色，快去创建第一个角色吧！">
        </el-empty>
      </div>
    </div>

    <!-- 角色详情弹窗 -->
    <el-dialog
      v-model="showDetailDialog"
      title="角色详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="detailLoading" class="detail-loading">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else-if="selectedCharacter" class="character-detail">
        <div class="detail-header">
          <div class="detail-avatar">
            <el-avatar :size="100" :src="selectedCharacter.image" :icon="User" />
          </div>
          <div class="detail-info">
            <h2 class="detail-name">{{ selectedCharacter.name }}</h2>
            <p class="detail-appearance">{{ selectedCharacter.appearance }}</p>
            <el-tag :type="selectedCharacter.isPublic ? 'success' : 'info'">
              {{ selectedCharacter.isPublic ? '公开角色' : '私有角色' }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <div class="detail-section">
            <h3 class="section-title">背景故事</h3>
            <p class="section-content">{{ selectedCharacter.background }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">性格特点</h3>
            <p class="section-content">{{ selectedCharacter.personality }}</p>
          </div>
          
          <div class="detail-section">
            <h3 class="section-title">经典台词</h3>
            <p class="section-content">{{ selectedCharacter.classicLines }}</p>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
          <el-button type="primary" @click="startChat">
            开始对话
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Plus } from '@element-plus/icons-vue'
import { characterApi } from '../api/character'
import type { Character } from '../api/character'

const router = useRouter()

// 响应式数据
const characters = ref<Character[]>([])
const charactersLoading = ref(false)
const showDetailDialog = ref(false)
const detailLoading = ref(false)
const selectedCharacter = ref<Character | null>(null)

// 角色详情缓存
const charactersCache = new Map<string, Character>()

// 获取用户角色列表
const fetchCharacters = async () => {
  try {
    charactersLoading.value = true
    const response = await characterApi.getUserCharacters()
    console.log('我的角色列表响应:', response)
    
    // 后端返回结构：{ code, msg, data: { characters: Character[] } }
    if (response && typeof response === 'object') {
      const success = response.code === 0 || response.code === 1
      if (success && response.data && Array.isArray(response.data.characters)) {
        characters.value = response.data.characters
        return
      }
    }
    
    // 如果响应格式不符合预期，抛出错误
    throw new Error(response?.msg || '获取我的角色列表失败')
  } catch (error: any) {
    console.error('获取我的角色列表失败:', error)
    ElMessage.error('获取我的角色列表失败: ' + (error.message || error))
    characters.value = [] // 确保在错误时也有默认值
  } finally {
    charactersLoading.value = false
  }
}

// 显示角色详情
const showCharacterDetail = async (characterId: number) => {
  try {
    showDetailDialog.value = true
    
    // 检查缓存
    if (charactersCache.has(characterId.toString())) {
      selectedCharacter.value = charactersCache.get(characterId.toString())!
      return
    }
    
    detailLoading.value = true
    const response = await characterApi.getDetail(characterId)
    // 根据API返回格式：{code, msg, data: Character}
    selectedCharacter.value = response.data
    
    // 缓存角色详情
    if (response.data) {
      charactersCache.set(characterId.toString(), response.data)
    }
  } catch (error: any) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败，请重试')
    showDetailDialog.value = false
  } finally {
    detailLoading.value = false
  }
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  showDetailDialog.value = false
  selectedCharacter.value = null
}

// 开始对话
const startChat = () => {
  if (selectedCharacter.value) {
    const id = selectedCharacter.value.id as number
    // 生成一个可复用的会话记忆ID（同一角色固定，便于保持上下文）
    const memoryId = `char-${id}`
    showDetailDialog.value = false
    router.push({
      name: 'Chat',
      params: { id: String(id) },
      query: { memoryId }
    })
  }
}

// 编辑角色
const editCharacter = (characterId: number) => {
  ElMessage.info('编辑功能即将上线，敬请期待！')
  // TODO: 实现编辑角色功能
  // router.push(`/app/edit-character/${characterId}`)
}

// 删除角色
const deleteCharacter = async (characterId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个角色吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    ElMessage.info('删除功能即将上线，敬请期待！')
    // TODO: 实现删除角色功能
    // const response = await characterApi.delete(characterId)
    // if (response.code === 1) {
    //   ElMessage.success('角色删除成功！')
    //   await fetchCharacters() // 刷新列表
    // }
  } catch {
    // 用户取消删除
  }
}

// 跳转到创建角色页面
const goToCreateCharacter = () => {
  router.push('/app/create-character')
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 组件挂载时获取角色列表
onMounted(() => {
  fetchCharacters()
})
</script>

<style scoped>
.my-characters {
  padding: 0;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  text-align: left;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.page-description {
  font-size: 16px;
  color: #be185d;
  margin: 0;
}

.character-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 80px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.character-card {
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid #f9a8d4;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  padding: 20px;
  min-height: 120px;
}

.character-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(236, 72, 153, 0.1), transparent);
  transition: left 0.5s;
}

.character-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 12px 35px rgba(236, 72, 153, 0.2);
  border-color: #ec4899;
}

.character-card:hover::before {
  left: 100%;
}

.character-card:active {
  transform: translateY(-4px) scale(1.01);
  transition: all 0.1s ease;
}

.character-avatar {
  flex-shrink: 0;
  margin-right: 20px;
}

.character-info {
  flex: 1;
  text-align: left;
  margin-right: 20px;
}

.character-name {
  font-size: 18px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.character-desc {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.character-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.create-time {
  font-size: 12px;
  color: #999;
}

.character-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
  min-width: 80px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  width: 100%;
}

.loading-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

/* 角色详情弹窗样式 */
.character-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-avatar {
  margin-right: 20px;
  flex-shrink: 0;
}

.detail-info {
  flex: 1;
}

.detail-name {
  font-size: 24px;
  font-weight: bold;
  color: #ec4899;
  margin: 0 0 10px 0;
}

.detail-appearance {
  font-size: 16px;
  color: #be185d;
  margin: 0 0 10px 0;
  line-height: 1.5;
}

.detail-content {
  space-y: 20px;
}

.detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #ec4899;
  margin: 0 0 10px 0;
  padding-bottom: 5px;
  border-bottom: 2px solid #f9a8d4;
}

.section-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin: 0;
  padding: 10px 0;
}

.detail-loading {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .character-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 15px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .character-actions {
    flex-direction: column;
  }
  
  .character-actions .el-button {
    width: 100%;
  }
}
</style>